package top.cardone.data.support.impl;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import top.cardone.data.support.PageableSupport;

import java.util.Map;

/**
 * Created by yao hai tao on 2015/8/9.
 */
public class PageableSupportImpl implements PageableSupport {
    /**
     * 排序集合
     */
    @lombok.Setter
    private String directionParam = "direction";

    /**
     * 页面代码参数名
     */
    @lombok.Setter
    private String pageParam = "pageNumber";

    /**
     * 属性集合
     */
    @lombok.Setter
    private String propertiesParam = "properties";

    /**
     * 分页行数大小
     */
    @lombok.Setter
    private int size = 10;

    /**
     * 分页行数大小参数名
     */
    @lombok.Setter
    private String sizeParam = "pageSize";

    @Override
    public Pageable newPageable(Map<String, ?> paramMap) {
        int page = Math.max(MapUtils.getIntValue(paramMap, this.pageParam, 1), 1) - 1;

        int size = MapUtils.getIntValue(paramMap, this.sizeParam, this.size);

        String propertiesString = MapUtils.getString(paramMap, this.propertiesParam);

        if (StringUtils.isEmpty(propertiesString)) {
            return new PageRequest(page, size);
        }

        String[] properties = propertiesString.split(",");

        if (ArrayUtils.isEmpty(properties)) {
            return new PageRequest(page, size);
        }

        String directionString = MapUtils.getString(paramMap, this.directionParam);

        Sort.Direction directio = Sort.Direction.fromStringOrNull(directionString);

        if (directio == null) {
            directio = Sort.Direction.DESC;
        }

        return new PageRequest(page, size, directio, properties);
    }
}
